var area = require('../../../dist/area')
var util = require('../../../utils/util.js');
var api = require('../../../config/api.js');
var p = 0,
  c = 0,
  d = 0
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    toast1Hidden: true,
    modalHidden: true,
    modalHidden2: true,
    notice_str: '',

    provinceName: [],
    provinceCode: [],
    provinceSelIndex: '',
    cityName: [],
    cityCode: [],
    citySelIndex: '',
    districtName: [],
    districtCode: [],
    districtSelIndex: '',
    showMessage: false,
    messageContent: '',
    showDistpicker: false,

    isAgree: false,

    pronm: "",
    citnm: "",
    cotnm: "",

    id: "",

  },


  bindAgreeChange: function (e) {
    this.setData({
      isAgree: !!e.detail.value.length
    });
  },

  toast1Change: function (e) {
    this.setData({
      toast1Hidden: true
    });
  },

  //表单提交
  formSubmit: function (e) {
    var that = this;
    wx.showModal({
      title: '提示',
      content: '是否确认保存',
      confirmColor: "#FF7D7C",
      success: (res) => {
        wx.showLoading({
          title: '加载中',
        })

        var provinceName = that.data.provinceName[that.data.provinceSelIndex]
        var cityName = that.data.cityName[that.data.citySelIndex]
        var districtName = that.data.districtName[that.data.districtSelIndex]
        var deptAddress = provinceName + cityName + districtName + e.detail.value.address
        console.log("provinceName" + provinceName)

        if (res.confirm) {
          console.log('for发生了submit事件，携带数据为：', e.detail.value);

          var reg = /^[0-9a-zA-Z]+$/;
          var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/;


          if (e.detail.value.trueName.length == 0) {
            wx.showToast({
              title: "收货人姓名不能为空!",
              icon: 'none',
              duration: 2000
            });
            return false;
          } else if (e.detail.value.mobile.length == 0) {
            wx.showToast({
              title: "手机号码不能为空!",
              icon: 'none',
              duration: 2000
            });
            return false;
          } else if (e.detail.value.mobile.length != 11) {
            wx.showToast({
              title: "手机号长度不正确!",
              icon: 'none',
              duration: 2000
            });
            return false;
          } else if (!myreg.test(e.detail.value.mobile)) {
            wx.showToast({
              title: '手机号格式有误！',
              icon: 'none',
              duration: 1500
            })
            return false;
          } else if (that.data.provinceSelIndex == "" && that.data.provinceSelIndex !== 0) {
            wx.showToast({
              title: "请选择并确定收货地区!",
              icon: 'none',
              duration: 2000
            });
            return false;
          } else if (e.detail.value.address.length == 0) {
            wx.showToast({
              title: "详细地址不能为空!",
              icon: 'none',
              duration: 2000
            });
            return false;
          }

          var data = {
            id: that.data.id,
            userName: e.detail.value.trueName,
            telNumber: e.detail.value.mobile,
            provinceName: provinceName,
            cityName: cityName,
            countyName: districtName,
            detailInfo: e.detail.value.address,
            tokenType: 1
          }

          util.req(api.AddressDefult, data, "POST").then(function (res) {
            wx.showLoading({
              title: '加载中',
            })

            if (res.success) {
              wx.showModal({
                title: '提示',
                content: res.msg,
                confirmColor: "#FF7D7C",
                showCancel: false,
                success: function (res) {
                  if (res.confirm) {
                    console.log('用户点击确定')
                    wx.navigateBack({})
                  }
                }
              });
              wx.hideLoading();
            }
          }).catch(function (res) {
            console.log("获取数据失败！")
          })

        } else if (res.cancel) {
          console.log('用户点击取消')
          wx.hideLoading();
        }
      }
    })
  },


  cenc: function () {
    wx.navigateBack({})
  },

  //弹出确认框  
  modalTap: function (e) {
    this.setData({
      modalHidden: true
    })
  },
  confirm_one: function (e) {
    console.log(e);
    this.setData({
      modalHidden: true,
      toast1Hidden: false,
      notice_str: '提交成功'
    });
  },
  cancel_one: function (e) {
    console.log(e);
    this.setData({
      modalHidden: true,
      toast1Hidden: false,
      notice_str: '取消成功'
    });
  },
  //弹出提示框  
  modalTap2: function (e) {
    this.setData({
      modalHidden2: false
    })
  },
  modalChange2: function (e) {
    this.setData({
      modalHidden2: true
    })
  },

  bindPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index: e.detail.value
    })
  },

  //获取地址信息
  getAdressInfo: function () {
    var that = this
    var Id = that.data.id;
    util.req(api.AddressDetail + Id, {}, "GET").then(function (res) {
      if (res.success) {
        that.setData({
          pronm: res.obj.provinceName,
          citnm: res.obj.cityName,
          cotnm: res.obj.countyName,
          trueName: res.obj.userName,
          mobile: res.obj.telNumber,
          address: res.obj.detailInfo
        })
        that.pcc()
      } else {
        console.log("获取地址详情失败！")
      }
    }).catch(function (res) {
      console.log("获取数据失败！")
    })
  },

  //删除地址操作
  delt: function () {
    var that = this
    wx.showModal({
      title: '',
      content: '确定删除该地址？',
      confirmColor: "#FF7D7C",
      success: function (res) {
        if (res.confirm) {
          let addressId = that.data.id;
          var url = addressId
          console.log('url=' + url)
          util.req(api.AddressDelete + url, {}, "GET").then(function (res) {
            if (res.success) {
              wx.showToast({
                title: '删除成功',
                icon: 'success',
                duration: 2000
              })
              wx.navigateBack({})
            } else {
              console.log("地址状态修改不成功")
            }
          }).catch(function (res) {
            console.log("获取数据失败！")
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */   
  onLoad: function (options) {
    var that = this
    this.setAreaData()
    var that = this
    //修改地址信息
    that.setData({
      id: options.id
    })

    that.getAdressInfo()
  },

  //转译地址
  pcc: function () {
    var that = this

    var pronm = that.data.pronm
    var citnm = that.data.citnm
    var cotnm = that.data.cotnm

    var provinceName = that.data.provinceName;
    var provinceCode = that.data.provinceCode;
    var cityName = [];
    var cityCode = [];
    var districtName = [];
    var districtCode = [];
    for (var i = 0; i < provinceCode.length; i++) {
      if (pronm == provinceName[i]) {
        var city = area[provinceCode[i]]
        for (var item in city) {
          cityName.push(city[item])
          cityCode.push(item)
        }
        that.setData({
          cityName: cityName,
          cityCode: cityCode
        })
        for (var j = 0; j < cityCode.length; j++) {
          if (citnm == cityName[j]) {
            var district = area[cityCode[j]]
            for (var item in district) {
              districtName.push(district[item])
              districtCode.push(item)
            }
            that.setData({
              districtName: districtName,
              districtCode: districtCode
            })
            for (var k = 0; k < districtCode.length; k++) {
              if (cotnm == districtName[k]) {
                that.setData({
                  provinceSelIndex: i,
                  citySelIndex: j,
                  districtSelIndex: k,
                })
                return true;
              }
            }
          }
        }
      }
    }
  },

  setAreaData: function (p, c, d) {
    var p = p || 0 // provinceSelIndex
    var c = c || 0 // citySelIndex
    var d = d || 0 // districtSelIndex
    // 设置省的数据
    var province = area['100000']
    var provinceName = [];
    var provinceCode = [];
    for (var item in province) {
      provinceName.push(province[item])
      provinceCode.push(item)
    }
    this.setData({
      provinceName: provinceName,
      provinceCode: provinceCode
    })
    // 设置市的数据
    var city = area[provinceCode[p]]
    var cityName = [];
    var cityCode = [];
    for (var item in city) {
      cityName.push(city[item])
      cityCode.push(item)
    }
    this.setData({
      cityName: cityName,
      cityCode: cityCode
    })
    // 设置区的数据
    var district = area[cityCode[c]]
    var districtName = [];
    var districtCode = [];
    for (var item in district) {
      districtName.push(district[item])
      districtCode.push(item)
    }
    this.setData({
      districtName: districtName,
      districtCode: districtCode
    })
  },
  changeArea: function (e) {
    p = e.detail.value[0]
    c = e.detail.value[1]
    d = e.detail.value[2]
    this.setAreaData(p, c, d)
  },
  showDistpicker: function () {
    this.setData({
      showDistpicker: true
    })
  },
  distpickerCancel: function () {
    this.setData({
      showDistpicker: false
    })
  },
  distpickerSure: function () {
    this.setData({
      provinceSelIndex: p,
      citySelIndex: c,
      districtSelIndex: d
    })
    this.distpickerCancel()
  },
  showMessage: function (text) {
    var that = this
    that.setData({
      showMessage: true,
      messageContent: text
    })
    setTimeout(function () {
      that.setData({
        showMessage: false,
        messageContent: ''
      })
    }, 3000)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})